using System;
using System.Collections.Generic;
using System.Linq;
using AtomicCms.Common.IDataContext;
using AtomicCms.Common.IServices;
using AtomicCms.Common.Logging;
using AtomicCms.Common.Models;

namespace AtomicCms.Services
{
    public class WidgetService : IWidgetService
    {
        private readonly IAtomicCmsDataRepository _dataContext;
        private readonly ILoggingService _log;

        public WidgetService(IAtomicCmsDataRepository dataContext, ILoggingService log)
        {
            _dataContext = dataContext;
            _log = log;
        }

        #region IWidgetService Members

        public IList<TagCount> GetTagCounts()
        {
            try
            {
                ICollection<PageTag> pagesTags = _dataContext.GetPagesTags();
                IEnumerable<IGrouping<Tag, PageTag>> groupedTagsPages = from pt in pagesTags
                                                                        group pt by pt.Tag
                                                                        into g
                                                                        select g;
                var groupedTagsCount = from rr in groupedTagsPages
                                       select new {Tag = rr.Key, Count = rr.Count()};

                var tagCount = new List<TagCount>(groupedTagsCount.Count());
                tagCount.AddRange(groupedTagsCount.Select(pageTags => new TagCount {Tag = pageTags.Tag, Count = pageTags.Count}));

                return tagCount;
            }
            catch (Exception ex)
            {
                _log.Exception(ex);
                throw;
            }
        }

        #endregion
    }
}